package com.itheima.stock.service.impl;

import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.entity.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service("UserService")
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public SysUser findByUserName(String userName) {
        return sysUserMapper.findUserInfoByUserName(userName);
    }

    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        //1.判断参数是否合法
        if (vo==null|| StringUtils.isBlank(vo.getUsername())||StringUtils.isBlank(vo.getPassword())) {
            return R.error(ResponseCode.DATA_ERROR);
        }
        //2.根据用户名去数据库查询用户信息，获取密码的密文
        SysUser userInfoByUserName = sysUserMapper.findUserInfoByUserName(vo.getUsername());
        if (userInfoByUserName==null) {
            return R.error(ResponseCode.ACCOUNT_NOT_EXISTS);
        }

        //3.调用密码匹配器匹配输入的明文密码和数据库的密文密码
        boolean matches = passwordEncoder.matches(vo.getPassword(), userInfoByUserName.getPassword());
        if (! matches) {
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
        }


        //4.响应
        return R.ok(new LoginRespVo(userInfoByUserName.getId(),userInfoByUserName.getUsername(),userInfoByUserName.getNickName(),userInfoByUserName.getPhone()));
    }
}
